<template>
  <div>
    <van-search shape="round"
      placeholder="请输入搜索关键词"
      v-model="value"
      @input="onInput"/>

    <div class="hotSearch" v-if="!searchRes.length">
      <p class="hotTit">热门搜索</p>
      <div class="hotTags">
        <span v-for="item in hotSearch" :key="item.first"
        @click="onClick(item.first)">{{item.first}}</span>
      </div>
    </div>

    <div class="searchRes" v-else>
      <p class="hotTit">最新匹配</p>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <MusicItem v-for="(item, index) in searchRes" :key="index"
          :name='item.name'
          :artistsName='item.ar[0].name'
        />
      </van-list>
    </div>
  </div>
</template>

<script>
import { getHotSearch, getSearchRes } from '@/api/search.js'
import MusicItem from '@/components/MusicItem.vue'
export default {
  name: 'search',
  data () {
    return {
      value: '',
      hotSearch: [],
      searchRes: [],
      list: [],
      loading: false,
      finished: false,
      offset: 0,
      page: 1
    }
  },

  created () {
    this.loadSearch()
  },

  methods: {
    async loadSearch () {
      const res = await getHotSearch()
      // console.log(res)
      this.hotSearch = res.data.result.hots
    },
    async onClick (name) {
      this.value = name
      const res = await getSearchRes({
        keywords: this.value,
        limit: 10
      })
      this.searchRes = res.data.result.songs
    },
    onInput () {
      this.page = 1
      if (this.value === '') {
        this.searchRes = []
        clearTimeout(this.id)
        return
      }
      if (this.id) clearTimeout(this.id)
      this.id = setTimeout(async () => {
        const res = await getSearchRes({
          keywords: this.value,
          limit: 10
        })
        this.searchRes = res.data.result.songs
      }, 1000)
    },
    async onLoad () {
      this.page++
      const res = await getSearchRes({
        keywords: this.value,
        limit: 10,
        offset: (this.page - 1) * 10
      })
      if (res.data.result.songs) {
        this.searchRes.push(...res.data.result.songs)
        this.loading = false
      } else {
        this.finished = true
      }
    }
  },
  components: {
    MusicItem
  }
}
</script>

<style scoped>
.hotTit{
  font-size: 13px;
  color: #999;
  padding-left: 10px;
}
.hotTags span{
  display: inline-block;
  font-size: 14px;
  border:1px solid #ccc ;
  color: #999;
  border-radius: 15px;
  padding: 5px 8px;
  margin: 7px 5px;
}
</style>
